<?php
/**
 * Created by jinqiang on 2024/7/31 18:04.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Repository;


class NNuoRepository
{
    const TOKEN = "15683e1492f0ec9e0ff26d066bfvztes"; //访问令牌

    const APPKEY = "13495150";//正式环境

    const APPSECRET = "BF9FAB937CFB4113";//正式环境

    const TAXNUM = "91330110MA2H2FJN7J";//ISV下授权商户税号，自用型应用置""即可

    const URL = "https://sdk.nuonuo.com/open/v1/services"; //SDK请求地址 正式环境

    const SENID = '15683E1492F0EC9E0FF26D519010C16A'; //唯一标识，由企业自己生成32位随机码 91330110MA2H2FJN7J  加密MD5 32位大写

    const VERSION = "2.0.0";

    public static function sign($nonce, $body, $timestamp)
    {
        $urlInfo = parse_url(self::URL);
        if ($urlInfo === FALSE) {
            return ['code' => -1, 'msg' => 'url解析失败'];
        }
        $pieces = explode('/', $urlInfo["path"]);
        $appKey = self::APPKEY;
        $senid = self::SENID;
        $appSecret = self::APPSECRET;
        $signStr = "a={$pieces[3]}&l={$pieces[2]}&p={$pieces[1]}&k={$appKey}&i={$senid}&n={$nonce}&t={$timestamp}&f={$body}";

        $sign = base64_encode(hash_hmac("sha1", $signStr, $appSecret, true));
        return $sign;
    }

    public static function api($method, $content)
    {
        $nonce = rand(10000, 1000000000);
        $timestamp = time();
        $sign = self::sign($nonce, $content, $timestamp);
        $param = [
            'json' => $content,
            'headers' => [
                "Content-Type: application/json",
                "X-Nuonuo-Sign: {$sign}",
                "accessToken: ".self::TOKEN,
                "userTax: ".self::TAXNUM,
                "method: {$method}",
                "sdkVer: " . self::VERSION
            ]
        ];
        $finalUrl = self::URL."?senid=".self::SENID."&nonce={$nonce}&timestamp={$timestamp}&appkey=".self::APPKEY;
        $resp = httpCurl($finalUrl, $param);
        return json_decode($resp, true);
    }

    //开票结果查询接口
    public static function queryInvoiceResult($invoiceSerialNum)
    {
        $method = "nuonuo.ElectronInvoice.queryInvoiceResult"; //API方法名
        $body = json_encode(["serialNos" => $invoiceSerialNum, "isOfferInvoiceDetail" => 1], JSON_UNESCAPED_UNICODE);
        return self::api($method, $body);
    }

    //开票、冲红
    public static function requestBillingNew($content)
    {
        $method = "nuonuo.ElectronInvoice.requestBillingNew"; //API方法名
        return self::api($method, $content);
    }
}
